using AutoMapper;
using MediatR;
using Medical.Api.Write.Application.Command.BasicManagement.EquipmentPackageDictionaryCommand;
using Medical.Domain.BasicManagement;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Write.Application.Handler.BasicManagement.EquipmentPackageDictionaryHandler
{
    /// <summary>
    /// 创建器械包处理器
    /// </summary>
    public class CreateEquipmentPackageHandler : IRequestHandler<CreateEquipmentPackageCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<EquipmentPackage> _packageRepository;
        private readonly ILogger<CreateEquipmentPackageHandler> _logger;
        private readonly IMapper _mapper;
        private readonly Random _random;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="packageRepository">仓储</param>
        /// <param name="logger">日志记录器</param>
        /// <param name="mapper">对象映射器</param>
        public CreateEquipmentPackageHandler(
            IBaseRepository<EquipmentPackage> packageRepository,
            ILogger<CreateEquipmentPackageHandler> logger,
            IMapper mapper)
        {
            _packageRepository = packageRepository;
            _logger = logger;
            _mapper = mapper;
            _random = new Random();
        }

        /// <summary>
        /// 处理创建器械包请求
        /// </summary>
        /// <param name="request">创建命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>创建结果</returns>
        public Task<ApiResult<int>> Handle(CreateEquipmentPackageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 使用AutoMapper创建实体
                var package = _mapper.Map<EquipmentPackage>(request.PackageData);

                // 设置默认状态为启用(1)
                package.Status = 1;
                package.IsDeleted = false;
                package.CreateTime = DateTime.Now;
                package.UpdateTime = DateTime.Now;

                // 生成条形码：BC+四位随机数
                package.Barcodes = GenerateBarcodeNumber();

                // 生成器械包编号（与条形码相同）
                package.PackageCode = package.Barcodes;

                // 保存到数据库
                _packageRepository.Create(package);

                _logger.LogInformation("成功创建器械包 {Name}，ID: {Id}，条形码: {Barcode}",
                    package.PackageName, package.Id, package.Barcodes);

                return Task.FromResult(new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Msg = "创建成功",
                    Data = package.Id
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建器械包时发生异常");
                return Task.FromResult(new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = "创建失败：系统内部错误",
                    Data = 0
                });
            }
        }

        /// <summary>
        /// 生成条形码：BC+四位随机数
        /// </summary>
        /// <returns>生成的条形码</returns>
        private string GenerateBarcodeNumber()
        {
            // 生成四位随机数
            int randomNumber = _random.Next(1000, 10000); // 1000-9999之间的随机数
            string barcode = $"BC{randomNumber:D4}";

            // 检查条形码是否已存在，如果存在则重新生成
            while (_packageRepository.GetAll().Any(p => p.Barcodes == barcode))
            {
                randomNumber = _random.Next(1000, 10000);
                barcode = $"BC{randomNumber:D4}";
            }

            return barcode;
        }
    }
}